# -*- coding: utf-8 -*-
"""
股票数据模型
"""

from dataclasses import dataclass
from datetime import datetime, date
from typing import Optional


@dataclass
class StockInfo:
    """股票基础信息"""
    code: str                    # 股票代码
    name: Optional[str] = None   # 股票名称
    current_price: Optional[float] = None   # 当前价格
    open_price: Optional[float] = None      # 开盘价
    close_price: Optional[float] = None     # 收盘价
    change_percent: Optional[float] = None  # 涨跌幅
    volume: Optional[int] = None            # 成交量
    turnover: Optional[float] = None        # 成交额


@dataclass
class ZbfxRecord:
    """zbfx表记录"""
    id: int
    stock_code: str
    reason: str
    strength: float
    dtm: datetime


@dataclass
class AggregatedZbfxRecord:
    """聚合后的zbfx表记录"""
    stock_code: str
    aggregated_reason: str      # 合并后的推荐理由
    max_strength: float         # 最大强度值
    avg_strength: float         # 平均强度值
    sum_strength: float         # 累加强度值
    weighted_strength: float    # 加权强度值（用于最终排序）
    record_count: int          # 原始记录数量
    dtm: datetime              # 最新记录时间
    selection_type: str = ''   # 选择类型：'HIGH' 或 'LOW'
    
    def __post_init__(self):
        """初始化后处理"""
        # 默认使用最大强度作为加权强度
        if self.weighted_strength == 0:
            self.weighted_strength = self.max_strength


@dataclass
class MnjtRecord:
    """mnjt表记录"""
    id: Optional[int] = None
    code: str = ''
    reason: str = ''
    score: float = 0.0
    buy_jiage: float = 0.0
    buy_dtm: Optional[date] = None
    jiage: float = 0.0
    zhangfu: float = 0.0
    days: int = 1
    isend: str = 'N'
    
    def __post_init__(self):
        """初始化后处理"""
        if self.buy_dtm is None:
            self.buy_dtm = date.today()


@dataclass  
class TradeRecord:
    """交易记录"""
    stock_code: str
    stock_name: str
    reason: str
    score: float
    buy_price: float
    buy_time: datetime
    current_price: float = 0.0
    change_percent: float = 0.0
    days_held: int = 1
    is_active: bool = True
    
    def calculate_profit(self) -> float:
        """计算收益率"""
        if self.buy_price > 0:
            return (self.current_price - self.buy_price) / self.buy_price
        return 0.0
    
    def to_mnjt_record(self) -> MnjtRecord:
        """转换为MnjtRecord"""
        return MnjtRecord(
            code=self.stock_code,
            reason=self.reason,
            score=self.score,
            buy_jiage=self.buy_price,
            buy_dtm=self.buy_time.date(),
            jiage=self.current_price,
            zhangfu=self.change_percent,
            days=self.days_held,
            isend='N' if self.is_active else 'Y'
        )
